package com.module.StationFinder.AsyncTask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.text.Html;
import com.activity.gaswatchermtl.R;
import com.activity.gaswatchermtl.StartActivity;
import com.module.StationFinder.GasStationFinder;
import com.module.StationFinder.StationList;

/**
 * Background Async Task to Load Google places
 * */
public class LoadNearGasStationTask extends AsyncTask<String, String, String>  {
	
	private boolean executionEnded_ = false;

	private StartActivity callingActivity_ = null;

	private ProgressDialog progessDialog_ = null;

	private StationList listStation_ = null;

	private GasStationFinder stationFinder_ = null;

	private double latitude_ = 0.0;
	private double longitude_ = 0.0;
	private double radius_ = 0.0;

	public LoadNearGasStationTask(StartActivity activity, double latitude, double longitude, double radius) {
		callingActivity_ = activity;
		latitude_ = latitude;
		longitude_ = longitude;
		radius_ = radius;
	}

	/**
	 * Before starting background thread Show Progress Dialog
	 * */
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		executionEnded_ = false;
		progessDialog_ = new ProgressDialog(callingActivity_);
		progessDialog_.setMessage(Html.fromHtml(callingActivity_.getString(R.string.loading_station)));
		progessDialog_.setIndeterminate(false);
		progessDialog_.setCancelable(false);
		progessDialog_.show();
	}

	/**
	 * getting Places JSON
	 * */
	@Override
	protected String doInBackground(String... args) {
		// creating Places class object
		stationFinder_ = new GasStationFinder();

		try {
			// get nearest places
			listStation_ = stationFinder_.search(latitude_, longitude_, radius_);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * After completing background task Dismiss the progress dialog
	 * **/
	@Override
	protected void onPostExecute(String file_url) {		
		// dismiss the dialog after getting all products
		progessDialog_.dismiss();
		executionEnded_ = true;
		callingActivity_.onStationListUpdated();
	}
	
	public StationList getStationList() {
		return listStation_;
	}
	
	public boolean isExecutionFinished(){
		return executionEnded_;
	}
}
